package com.pocketsweet.chat.ui.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.model.MLLovers;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_random_call_matching)
public class RandomCallMatchingActivity extends BaseActivity {
    @ViewInject(R.id.llMatchContent)
    private LinearLayout llMatchContent;

    @ViewInject(R.id.ibClose)
    private ImageView ibClose;

    @ViewInject(R.id.ivMatch)
    private ImageView ivMatch;

    @ViewInject(R.id.FiveTimer)
    private Chronometer FiveTimer;

    @ViewInject(R.id.ThirtyTimer)
    private Chronometer ThirtyTimer;

    private Context ctx;
    public static RandomCallMatchingActivity _instance;
    private MLUser currentUser;
    private int status;
    private boolean fistRun = true;
    boolean isCalling = false;

    public static MLLovers curLover;

    private final int[] playBg = {R.drawable.icon_match3,
            R.drawable.icon_match2, R.drawable.icon_match1};
    private final int CALLICON = 0x01;
    private final int FIVE = 0x02;
    private final int THIRTY = 0x03;
    private int playNum = 0;
    private int fiveNum = 0;
    private int ThrityNum = 0;
    public Timer CallIconTimer;
    public Timer FiveSecTimer;
    public Timer ThritySecTimer;
    public TimerTask callTimerTask = new TimerTask() {

        @Override
        public void run() {
            playNum++;
            if (playNum > 2) {
                playNum = 0;
            }
            Message message = new Message();
            message.what = CALLICON;
            handler.sendMessage(message);
        }
    };
    public TimerTask fiveTimerTask = new TimerTask() {

        @Override
        public void run() {
            fiveNum++;
            if (fiveNum > 5) {
                fiveNum = 0;
            }
            if (fiveNum == 5) {
                startCall();
            }
            Message message = new Message();
            message.what = FIVE;
            handler.sendMessage(message);
        }
    };
    public TimerTask thirtyTimerTask = new TimerTask() {

        @Override
        public void run() {
            ThrityNum++;
            if (ThrityNum > 30) {
                ThrityNum = 0;
            }
            Message message = new Message();
            message.what = THIRTY;
            handler.sendMessage(message);
        }
    };

    private Handler handler = new Handler() {
        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CALLICON:
                    Drawable bg = ctx.getResources().getDrawable(playBg[playNum]);

                    // ivMatch.setBackground(bg);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        ivMatch.setBackground(bg);
                    } else {
                        ivMatch.setBackgroundDrawable(bg);
                    }
                    break;

                case FIVE:
                    break;

                case THIRTY:
                    if (ThrityNum == 30) {
                        opentTip();
                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        currentUser = UserService.getCurrentUser();
        ctx = this;
        _instance = this;
        initComponent();
        AddToRandomPoll();
    }

    @Override
    protected void onResume() {
        if (fistRun != true) {
            isCalling = false;
            if (isCalling == false
                    && currentUser.getGender() == C.USER_GENDER_MALE) {
                fiveNum = 0;
                if (FiveSecTimer != null) {
                    FiveSecTimer.cancel();
                }
                FiveSecTimer = new Timer();
                FiveSecTimer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        fiveNum++;
                        if (fiveNum > 5) {
                            fiveNum = 0;
                        }
                        if (fiveNum == 5) {
                            startCall();
                        }
                        Message message = new Message();
                        message.what = FIVE;
                        handler.sendMessage(message);

                    }
                }, 1000, 1000);

                ThrityNum = 0;
                if (ThritySecTimer != null) {
                    ThritySecTimer.cancel();
                }
                ThritySecTimer = new Timer();
                ThritySecTimer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        ThrityNum++;
                        if (ThrityNum > 30) {
                            ThrityNum = 0;
                        }
                        Message message = new Message();
                        message.what = THIRTY;
                        handler.sendMessage(message);

                    }

                }, 1000, 1000);
            }

        }
        fistRun = false;
        super.onResume();
    }

    public static MLLovers getCurLover() {
        return curLover;
    }

    public static RandomCallMatchingActivity getInstance() {
        return _instance;
    }

    private void opentTip() {
        FiveSecTimer.cancel();
        ThritySecTimer.cancel();
        View itemView = View.inflate(this, R.layout.view_andomcall_tip, null);
        final MyAlertDialog dialog = new MyAlertDialog(
                RandomCallMatchingActivity.this).builder().setView(itemView)
                .setNegativeButton("再等等", new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isCalling == false
                                && currentUser.getGender() == C.USER_GENDER_MALE) {
                            fiveNum = 0;
                            if (FiveSecTimer != null) {
                                FiveSecTimer.cancel();
                            }
                            FiveSecTimer = new Timer();
                            FiveSecTimer.schedule(new TimerTask() {

                                @Override
                                public void run() {
                                    fiveNum++;
                                    if (fiveNum > 5) {
                                        fiveNum = 0;
                                    }
                                    if (fiveNum == 5) {
                                        startCall();
                                    }
                                    Message message = new Message();
                                    message.what = FIVE;
                                    handler.sendMessage(message);

                                }
                            }, 1000, 1000);

                            ThrityNum = 0;
                            if (ThritySecTimer != null) {
                                ThritySecTimer.cancel();
                            }
                            ThritySecTimer = new Timer();
                            ThritySecTimer.schedule(new TimerTask() {

                                @Override
                                public void run() {
                                    ThrityNum++;
                                    if (ThrityNum > 30) {
                                        ThrityNum = 0;
                                    }
                                    Message message = new Message();
                                    message.what = THIRTY;
                                    handler.sendMessage(message);

                                }

                            }, 1000, 1000);
                        }
                    }
                });
        dialog.setPositiveButton("情感热线", new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main.rlLoverInvited.setVisibility(View.VISIBLE);
                RandomCallMatchingActivity.this.finish();
                // Intent intent = new Intent(RandomCallMatchingActivity.this,
                // DialogLoveCall.class);
                // RandomCallMatchingActivity.this.startActivity(intent);
                // RandomCallMatchingActivity.this.finish();
            }
        });
        dialog.setCancelable(false);
        dialog.show();
        dialog.setnoTitle();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (CallIconTimer != null) {
            CallIconTimer.cancel();
        }
        if (FiveSecTimer != null) {
            FiveSecTimer.cancel();
        }
        if (ThritySecTimer != null) {
            ThritySecTimer.cancel();
        }
        isCalling = false;
        super.onDestroy();
    }

    private void initComponent() {
        CallIconTimer = new Timer();
        CallIconTimer.schedule(callTimerTask, 250, 250);

        if (currentUser.getGender() == C.USER_GENDER_MALE) {
            FiveSecTimer = new Timer();
            FiveSecTimer.schedule(fiveTimerTask, 1000, 1000);

            ThritySecTimer = new Timer();
            ThritySecTimer.schedule(thirtyTimerTask, 1000, 1000);

        }
    }

    private void AddToRandomPoll() {
        AVQuery<MLLovers> query = new AVQuery<MLLovers>("MLLovers");
        query.whereEqualTo("user", currentUser);
        query.findInBackground(new FindCallback<MLLovers>() {

            @Override
            public void done(List<MLLovers> lovers, AVException e) {
                if (e == null) {
                    if (lovers.size() != 0) {
                        AVObject.deleteAllInBackground(lovers, null);
                    }
                    final MLLovers lover = new MLLovers();
                    lover.setUser(currentUser);
                    lover.setGender(currentUser.getGender());
                    lover.setStatus(C.CALL_STATUS_WAITING);
                    lover.saveInBackground(new SaveCallback() {

                        @Override
                        public void done(AVException e) {
                            if (e == null) {
                                curLover = lover;
                                if (currentUser.getGender() == C.USER_GENDER_MALE) {
                                    startCall();
                                }
                            } else {
                                ToolKits.toast(ctx, "加载失败，请检查网络");
                            }
                        }
                    });

                }
            }
        });
    }

    private void startCall() {
        // Log.e("开始打电话", "开始打电话");

        AVQuery<MLLovers> query = new AVQuery<MLLovers>("MLLovers");
        query.whereEqualTo("status", C.CALL_STATUS_WAITING);
        query.whereEqualTo("gender", C.USER_GENDER_FEMALE);
        query.include("user");
        query.findInBackground(new FindCallback<MLLovers>() {

            @Override
            public void done(List<MLLovers> users, AVException e) {
                if (e == null) {
                    if (users.size() != 0) {
                        int i = (int) (Math.random() * users.size());
                        MLUser user = users.get(i).getUser();
                        FiveSecTimer.cancel();
                        ThritySecTimer.cancel();
                        CallIconTimer.cancel();
                        isCalling = true;
                        startActivity(new Intent(ctx, RandomCallActivity.class)
                                .putExtra("username", user.getObjectId())
                                .putExtra("avatar", user.getAvatarUrl())
                                .putExtra("nickname", user.getNickname())
                                .putExtra("isComingCall", false));

                    } else {
                        // FiveTimer.setBase(SystemClock.elapsedRealtime());
                    }
                } else {

                }
            }
        });

    }

    // 点击关闭
    @OnClick(R.id.ibClose)
    public void onCloseClick(View v) {
        closePage();
        finish();
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closePage();

            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void closePage() {
        _instance = null;
        AVQuery<MLLovers> query = new AVQuery<MLLovers>("MLLovers");
        query.whereEqualTo("user", currentUser);
        query.findInBackground(new FindCallback<MLLovers>() {

            @Override
            public void done(List<MLLovers> users, AVException e) {
                if (e == null) {
                    if (users.size() != 0) {
                        users.get(0).deleteInBackground();
                    }
                } else {
                }
            }
        });
    }

}
